package com.yufeng.collaboration.controller;

import com.yufeng.collaboration.entity.User;
import com.yufeng.collaboration.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {
    @Autowired
    private UserService userService;

//    @GetMapping("user/{userId}")
//    public User getUserById(@PathVariable("userId") Integer userId) {
//        return userService.getUserById(userId);
//    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (userService.validLogin(user.getUsername(), user.getPassword())) {
                User loggedUser = userService.getUserByUsername(user.getUsername());
                response.put("id", loggedUser.getId());
                response.put("username", loggedUser.getUsername());
                response.put("email", loggedUser.getEmail());
                response.put("password", loggedUser.getPassword());
                response.put("description", loggedUser.getDescription());
            } else {
                response.put("message", "fail");
            }
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            response.put("message", "Internal server error during login");
        }
        return response;
    }

    @PostMapping("/regist")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        User existingUser = userService.getUserByUsername(user.getUsername());
        if (existingUser != null) {
            response.put("message", "fail");
        } else {
            userService.registerUser(user);
            response.put("message", "success");
        }
        return response;
    }

    @PostMapping("/modify_user_info")
    public Map<String, Object> modifyUserInfo(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        userService.modifyUserInfo(user);
        response.put("message", "success");
        return response;
    }
}
